﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using P2.Cuberry.Framework.Helper;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Unity;
using System.Windows;
using Microsoft.Practices.Prism.Events;

namespace P2.Cuberry.Modules.SimpleAccounting.FiCheque
{
    public class FiChequesTransactionButtonPresentationModel : INotifyPropertyChanged
    {

        public FiChequesTransactionButtonPresentationModel(IFiChequesTransactionButtonView view, Services.IFiChequeService service,
             IUnityContainer container, IEventAggregator eventAggregator)
        {
            try
            {
                View = view;
                Service = service;
                Container = container;
                this.eventAggregator = eventAggregator;
                MessageStack = new P2MessageStack();
                //find module access rights - used to determine, if button would be displayed
                var perm = new P2.Cuberry.Framework.Security.AccessPermissions();
                this.ModuleAccessRight = perm.ModuleAccessRight(Properties.Settings.Default.ModuleName);
                this.FiChequeOpenCommand = new DelegateCommand<object>(OnFiChequeOpenExecute, OnFiChequeOpenCanExecute);
                View.Presenter = this;
                this.RefreshView();
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }
        #region Public Properties
        //public Dictionary<string, P2.Cuberry.Framework.Security.User.ControlRight> ControlRights;
        protected bool SaveRight { get; set; }
        public IFiChequesTransactionButtonView View { get; set; }
        public BusinessEntities.FiCheque Model { get; set; }
        public Services.IFiChequeService Service { get; set; }
        public IUnityContainer Container { get; set; }
        private IEventAggregator eventAggregator;
        protected int ModuleAccessRight { get; set; }
        int? _fiTransactionItemID;

        public int? FiTransactionItemID
        {
            get
            {
                return _fiTransactionItemID;
            }
            set
            {
                _fiTransactionItemID = value;
                BusinessEntities.FiCheque editedItem = null;
                if (value.HasValue)
                {
                    // if transaction item ID is given, try to find cheque
                    editedItem = Service.RetrieveChequeByTransactionItemID(value.Value);
                    if (editedItem == null)
                    {
                        // if not found, create new instance and set fiscal year and transaction item id
                        editedItem = new BusinessEntities.FiCheque();
                        editedItem.FiTransactionID = this.FiTransactionItemID.Value;
                        if (this.FiscalYearID.HasValue)
                            editedItem.FiscalYearID = this.FiscalYearID.Value;
                    }

                }
                Model = editedItem;
                // check edit permission
                P2.Cuberry.Framework.Security.User.ControlRight controlRight;
                var controlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "FiChequesDetailsView");
                if (controlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
                    SaveRight = controlRight.IsActive;
                else
                    SaveRight = false;
                OnPropertyChanged("FiTransactionItemID");
                FiChequeOpenCommand.RaiseCanExecuteChanged();
            }
        }
        int? _fiscalYearID;
        public int? FiscalYearID
        {
            get
            {
                return _fiscalYearID;
            }
            set
            {
                _fiscalYearID = value;
                OnPropertyChanged("FiscalYearID");
            }
        }
        protected P2MessageStack myMessageStack = new P2MessageStack();
        public P2MessageStack MessageStack
        {
            get
            {
                return myMessageStack;
            }
            set
            {
                myMessageStack = value;
                OnPropertyChanged("MessageStack");
            }
        }
        #endregion

        #region Commands

        public DelegateCommand<object> FiChequeOpenCommand { get; set; }

        void OnFiChequeOpenExecute(object sourceAccount)
        {
            // on button click
            if (this.Model != null)
            {
                // if FiCheque instance was created on FiTransactionItemID property set, open FiCheque detail view
                IFiChequesDetailsView dv = this.Container.Resolve<IFiChequesDetailsView>();
                Services.IFiChequeService service = this.Container.Resolve<Services.IFiChequeService>();
                FiChequesDetailsPresentationModel pm = new FiChequesDetailsPresentationModel(dv, this.Model, service, eventAggregator);
                pm.IsOpenedFromTransaction = true;
                dv.FlowDirection = (P2Translator.Culture.TextInfo.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight);
                dv.ShowDialog();
                pm.Dispose();
                pm = null;
                dv = null;
                this.RefreshView();

            }
            return;
        }

        bool OnFiChequeOpenCanExecute(object sourceAccount)
        {
            if (!this.FiTransactionItemID.HasValue || this.FiTransactionItemID.Value == -1)
                // if FiTransactionItemID is null or -1 (item not saved), do hide button
                return false;
            if (SaveRight || (ModuleAccessRight > 0 && Model != null && Model.FiChequeID > 0))
                // enable if:
                // 1. user has edit permission on FiCheque module - can create new association or view/edit existing
                // 2. user has read permission on FiCheque module and cheque is already assigned - can view existing association
                return true;
            else
                return false;
        }


        public void RefreshView()
        {
            try
            {

                OnPropertyChanged("FiTransactionItemID");

                this.FiChequeOpenCommand.RaiseCanExecuteChanged();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }



        #endregion

        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

    }
}
